package httpUtils

import (
	"net/http"
	"path"

	"gitee.com/DengAnbang/goutils/fileUtil"
	"net/url"
	"os"
	"strings"
)

func GetValueFormRequest(r *http.Request, key string) string {
	r.ParseForm()
	ct := r.Header.Get("Content-Type")
	if strings.Contains(ct, "multipart/form-data") {
		r.ParseMultipartForm(32 << 20)
		if r.MultipartForm != nil {
			values := r.MultipartForm.Value[key]
			if len(values) > 0 {
				return values[0]
			}
		}
	} else {
		return r.FormValue(key)
		//return r.PostFormValue(key)
		//return r.Form.Get(key)
	}
	return ""
}

//////////////////////////////////////
//文件服务
func FileHandle(mux *http.ServeMux, stripPrefix, resourceRootPath string) {
	mux.Handle(stripPrefix, http.StripPrefix(stripPrefix, fileHandler{RootPath: resourceRootPath}))
}

type fileHandler struct {
	RootPath string
}

func (f fileHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	values, _ := url.PathUnescape(r.URL.String())
	fileName := f.RootPath + values
	if fileUtil.PathExists(fileName) {
		f, _ := os.Stat(fileName)
		if !f.IsDir() {
			w.Header().Set("Content-Disposition", "attachment; filename="+path.Base(fileName))
			http.ServeFile(w, r, fileName)
			return
		}
	}
	http.NotFound(w, r)
}

////////////////////////////////////
